package com.expense.taglib;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import javax.servlet.jsp.JspException;
import javax.servlet.jsp.JspTagException;
import javax.servlet.jsp.JspWriter;
import javax.servlet.jsp.tagext.TagSupport;



import com.expense.util.Constants;
import com.expense.util.PaginatedList;

public class PaginateTag extends TagSupport {
	/**
	 * 
	 */
	private static final long serialVersionUID = 150848338515348102L;

	//private final Log log = LogFactory.getLog(PaginateTag.class);
	
	private String items;
	/**
	 * 标签开始
	 */
	public int doStartTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext.getRequest();
		HttpSession session = request.getSession();
		PaginatedList pList = (PaginatedList) request.getAttribute(this.getItems());
		if (pList != null) {
			int min_num = (pList.getCurrentPage() - 1) * pList.getPageSize()+ 1;
			request.setAttribute("min_num", min_num + "");
		} else {
			return SKIP_BODY;
		}
		return EVAL_PAGE;
	}

	/**
	 * 标签结束
	 */
	public int doEndTag() throws JspException {
		HttpServletRequest request = (HttpServletRequest) pageContext
				.getRequest();
		HttpSession session = request.getSession();
		PaginatedList pList = (PaginatedList) request.getAttribute(this.getItems());
		String action=(String)request.getAttribute(Constants.PAGINATED_ACTION);
		if(action!=null&&action.indexOf('?')==-1){
			action=action+"?ac=ac";
		}
		if(pList!=null) {
			writePage(pList.getPages(), pList.getCurrentPage(), pList
				.getPageSize(), pList.getTotleCount(),action);	
		}
		printJS();
		return EVAL_PAGE;
	}
	/**
	 * 功能: 写翻页内容
	 * 
	 * @param pages
	 *            总页数
	 * @param currentPage
	 *            当前页
	 * @param pageSize
	 *            每页记录数
	 * @param records
	 *            总记录数
	 * @throws JspException
	 */
	private void writePage(int pages, int currentPage, int pageSize, int records,String action)
			throws JspException {
		try {
			final JspWriter writer = pageContext.getOut();
			StringBuffer content = new StringBuffer();
			// 打印一个高度为1的表格
			content
					.append("<table border='0' cellpadding='0' cellspacing='0'>");
			content.append("<tr><td style='height:1'></td></tr></table>");

			content.append("<input type='hidden' name='page' value='1' />");
			content.append("<input type='hidden' name='act' value='"+action+"' />");
			content.append("<input type='hidden' name='pageSize' value='"
					+ pageSize + "' />");

			// 打印表格
			content
					.append("<TABLE border='0' cellpadding='0' cellspacing='0'>");
			content
					.append("<TBODY><TR><TD width='45%'>  </TD><TD align='right'>");
			content
					.append("<TABLE width='98%' border='0' cellpadding='0' cellspacing='0' class='paginate'>");
			content.append("<TR><TD width='90%' nowrap>&nbsp;&nbsp;&nbsp;");

			// 打印翻页内容
			if (currentPage <= 1) {
				content.append("<span class=\"zi1\" >首页&nbsp;上一页&nbsp;</span>");
			} else {
				content.append("<span class=\"zi1\" ><a href=\"javascript:gotoPage('"+action+"','1','"
						+ pageSize + "');\">首页</a>&nbsp;");
				content.append("<a href=\"javascript:gotoPage('"+action+"','"
						+ (currentPage - 1) + "','" + pageSize
						+ "');\">上一页</a>&nbsp;</span>");
			}
			if (currentPage >= pages) {
				content.append("<span class=\"zi1\" >下一页&nbsp;尾页&nbsp;</span>");
			} else {
				content.append("<span class=\"zi1\" ><a href=\"javascript:gotoPage('"+action+"','"
						+ (currentPage + 1) + "','" + pageSize
						+ "');\">下一页</a>&nbsp;");
				content.append("<a href=\"javascript:gotoPage('"+action+"','" + pages
						+ "','" + pageSize + "');\">尾页</a>&nbsp;</span>");
			}

			// 打印页次
			content
					.append("<span class=\"zi1\" >&nbsp;&nbsp;页次:"
							+ ((pages == 0) ? 0 : currentPage));
			content.append("/" + pages + "页&nbsp;");

			// 打印每页记录条数
			content
					.append("<SELECT name='selSize' class='srk' onchange=\"javascript:gotoPage('"+action+"','1',this.value);\">");
			content.append("<OPTION value='5'>5</OPTION>");
			content.append("<OPTION value='10' selected>10</OPTION>");
			content.append("<OPTION value='20'>20</OPTION>");
			content.append("<OPTION value='50'>50</OPTION>");
			content.append("<OPTION value='100'>100</OPTION>");
			content.append("</SELECT> 条/页&nbsp;&nbsp;");

			// 打印记录总数
			content.append("共" + records + "条记录&nbsp;&nbsp;");

			// 打印跳转到第几页
			content
					.append("转到第<SELECT name='selPage' class='srk' onchange=\"javascript:gotoPage('"+action+"',this.value,'"
							+ pageSize + "');\">");
			for (int i = 1; i <= pages; i++) {
				content.append("<OPTION value=" + i + " "
						+ ((i == currentPage) ? " selected" : "") + ">" + i
						+ "</OPTION>");
			}
			content.append("</select> 页 &nbsp;</span>");

			content.append("</TD></TR></TABLE>");
			content.append("</TD></TR></TBODY></TABLE>");

			// 打印一个高度为1的表格
			content
					.append("<table border='0' cellpadding='0' cellspacing='0'>");
			content.append("<tr><td style='height:2'></td></tr></table>");
			writer.print(content.toString());
		} catch (Exception e) {
			//log.trace(e);
			throw new JspTagException("PaginateTag: " + e.getMessage());
		}
	}

	/**
	 * 功能: 打印JavaScript
	 * 
	 * @throws JspException
	 */
	private void printJS() throws JspException {
		try {
			final JspWriter writer = pageContext.getOut();
			StringBuffer content = new StringBuffer();
			content.append("<SCRIPT language='JavaScript'>");
			content.append("makeSizes();");
			content.append("function gotoPage(path, page, pageSize) {");
			content.append("document.all.act.value=path;");
			content.append("document.all.page.value=page;");
			content.append("document.all.pageSize.value=pageSize;");
			content.append("document.location.href =encodeURI(path+'&page='+page+'&pageSize='+pageSize);}");	
			content.append("function makeSizes() {");
			content.append("var pageSize = document.all['pageSize'].value;");
			content.append("var sel=document.all['selSize'];");
			content.append("for(var i=0; i<=5; i++) {");
			content.append("if(sel.options[i] && sel.options[i].value==pageSize){");
			content.append("sel.options[i].selected=true;");
			content.append("break;}}}");
			content.append("</SCRIPT>");
			content.append("<style type=\"text/css\">");
			content.append(".zi1{font-size:12px;color:#4B7585;font-weight:bold;}");
			content.append("</style>");
			writer.print(content.toString());
		} catch (Exception e) {
			//log.trace(e);
			throw new JspTagException("PaginateTag: " + e.getMessage());
		}
	}

	public String getItems() {
		return items;
	}

	public void setItems(String items) {
		this.items = items;
	}
	
	
}
